/**
 * 通过模拟点击事件，关闭某些浮层组件
 */

import { throttle } from '@peng_kai/kit/libs/lodash-es';

// 气泡弹窗
const popoverClasses = ['ant-select-dropdown', 'ant-picker-dropdown'];
const popoverSelector = popoverClasses.map(cls => `.${cls}`).join(', ');

// 触发按钮
const ignoreEles = ['ant-select', 'ant-picker'];
const ignoreSelector = ignoreEles.map(cls => `.${cls}`).join(', ');

window.addEventListener('touchstart', (ev) => {
  const popoverEles = document.querySelectorAll(popoverSelector);
  const visiblePopoverEles = (Array.from(popoverEles) as HTMLElement[])
    .filter(ele => ele.offsetParent !== null);

  if (!visiblePopoverEles.length)
    return;

  const isClickInPopover = visiblePopoverEles.some(ele => ele.contains(ev.target as HTMLElement));
  if (isClickInPopover)
    return;

  const ignoreEles = document.querySelectorAll(ignoreSelector);
  const isClickInIgnore = Array.from(ignoreEles).some(ele => ele.contains(ev.target as HTMLElement));

  if (isClickInIgnore)
    return;

  const clickEv = new MouseEvent('mousedown', {
    view: window,
    bubbles: true,
    cancelable: true,
  });

  document.documentElement.dispatchEvent(clickEv);
});

window.addEventListener('scroll', throttle(() => {
  const eles = document.querySelectorAll('.ant-tooltip');
  const visibleEles = (Array.from(eles) as HTMLElement[])
    .filter(ele => ele.offsetParent !== null);

  if (!visibleEles.length)
    return;

  const clickEv = new MouseEvent('mousedown', {
    view: window,
    bubbles: true,
    cancelable: true,
  });
  document.documentElement.dispatchEvent(clickEv);
}, 2000, { leading: true, trailing: false }), { capture: true });
